﻿using FDStudio.Core.Container;
using FDStudio.Core.Entities;
using FDStudio.Core.Entities.Query;
using FDStudio.Core.Runtime;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq.Expressions;

namespace FDStudio.Core.Repositories
{
    /*
     CreatedOn: 2018-01-26
     CreatedBy: Jackie Lee(天宇遊龍)
     */
    /// <summary>
    /// 只读仓储
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class WriteOnlyRepository<T> : IWriteOnlyRepository<T> where T : class, IEntity
    {
        private IContainer _container;

        public WriteOnlyRepository()
        {
            _container = RuntimeContext.Current.Container;
        }

        public IRepositoryContext Context => _container.Resove<IWriteOnlyRepositoryContext>();

        public C RepositoryContext<C>() where C : IRepositoryContext
        {
            return (C)Context;
        }

        public bool Add(T model)
        {
            return RepositoryContext<IWriteOnlyRepositoryContext>().Add(model);
        }

        public bool Delete(long Id)
        {
            return RepositoryContext<IWriteOnlyRepositoryContext>().Delete<T>(m => m.Id == Id);
        }

        public bool Delete(T model)
        {
            return RepositoryContext<IWriteOnlyRepositoryContext>().Delete(model);
        }

        public bool Delete(Expression<Func<T, bool>> condition)
        {
            return RepositoryContext<IWriteOnlyRepositoryContext>().Delete(condition);
        }

        public int ExecuteNonQuery(string sql, object parameter, CommandType commandType = CommandType.Text)
        {
            return RepositoryContext<IWriteOnlyRepositoryContext>().ExecuteNonQuery(sql, parameter, commandType);
        }

        public bool Update(T model)
        {
            return RepositoryContext<IWriteOnlyRepositoryContext>().Update(model);
        }

        public void BeginTransaction()
        {
            RepositoryContext<IWriteOnlyRepositoryContext>().BeginTransaction();
        }

        public void CommitTransaction()
        {
            RepositoryContext<IWriteOnlyRepositoryContext>().CommitTransaction();
        }

        public void RollbackTransaction()
        {
            RepositoryContext<IWriteOnlyRepositoryContext>().RollbackTransaction();
        }
    }
}
